﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using static drawDong.WriteWorker;

namespace drawDong
{
    public partial class Replace2 : Form
    {
        private ArrayList filesCehck ;
        private string rootPath;
        private ArrayList dLinesCheck = new ArrayList();
        private ArrayList dLines = new ArrayList();//文件下面所有的数据

        private int rowCount = 0;
        private int itemSize = 0, itemSizeDown = 0;
        private string surroundTypeA;
        private string surroundTypeB;
        private string surroundTypeC;
        private string surroundTypeD;
        private string surroundTypeE;
        private string surroundTypeF;
        private string contenta;
        private string contentb;
        private string contentc;
        private string contentd;
        private string contente;
        private string contentf;
        private ArrayList replaceContentList = new ArrayList();

        public Replace2(string path, ArrayList files)
        {
            InitializeComponent();
            this.rootPath = path;
            this.filesCehck = files;
            this.label1.Text = this.rootPath;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            contenta = this.textBox1.Text.ToString().Trim();
            contentb = this.textBox2.Text.ToString().Trim();
            contentc = this.textBox3.Text.ToString().Trim();
            contentd = this.textBox4.Text.ToString().Trim();
            contente = this.textBox5.Text.ToString().Trim();
            contentf = this.textBox6.Text.ToString().Trim();

            if (contenta.Length <= 0 && contentb.Length <= 0 && contentc.Length <= 0 && contentd.Length <= 0 && contente.Length <= 0 && contentf.Length <= 0)
            {
                MessageBox.Show("请输入一个数字", "提示");
                return;
            }
            this.button1.Enabled = false;

            surroundTypeA = contenta.Length > 0 ? "A" : "";
            surroundTypeB = contentb.Length > 0 ? "B" : "";
            surroundTypeC = contentc.Length > 0 ? "C" : "";
            surroundTypeD = contentd.Length > 0 ? "D" : "";
            surroundTypeE = contente.Length > 0 ? "E" : "";
            surroundTypeF = contentf.Length > 0 ? "F" : "";

            Console.WriteLine(DateTime.Now.ToString());
            for (int i = 0; i < filesCehck.Count; i++)
            {
                string rePath = filesCehck[i].ToString();
                bianLi(rootPath + @"\" + rePath);
            }
            Console.WriteLine(DateTime.Now.ToString());
            this.button1.Enabled = true;
            WriteWorker.AddRange(replaceContentList);
            replaceContentList.Clear();
        }

        private void bianLi(string path)
        {

            //创建文件夹
            DirectoryInfo rootDir = new DirectoryInfo(path);
            Boolean exists = Directory.Exists(path);
            if (exists)//判断目录是否存在
            {
                FileInfo[] files = rootDir.GetFiles();
                for (int i = 0; i < files.Length; i++)
                {
                    FileInfo tit = files[i];
                    string filePath = tit.FullName;

                    if (filePath.EndsWith("x.txt"))
                    {
                        loadData(filePath.Replace("x.txt", ".txt"));
                        loadDataDown(filePath);
                        handleContent(filePath);
                        replaceContent(filePath);
                    }
                }
            }
            this.Close();
        }

        private void handleContent(string path)
        {
            string[] keysT;
            string[] valuesT;

            string surrounfP = GlobalVariables.surrounPath + @"\" + path.Replace(GlobalVariables.firPath, "").Replace("x.txt", "").Replace(".txt", "") + ".ini";
            INIHelper.GetAllKeyValues("AAA", out keysT, out valuesT, surrounfP);
            dLinesCheck.Clear();
            ArrayList keys = new ArrayList();
            ArrayList values = new ArrayList();
            for (int i = 0; i < keysT.Length; i++)
            {
                keys.Add(keysT[i]);
                values.Add(valuesT[i]);
            }
            
            //查询符合要求的字符所在的列
            string stype = surroundTypeA + surroundTypeB + surroundTypeC + surroundTypeD + surroundTypeE + surroundTypeF;
            foreach (dLine item in dLines)
            {
                string itemValue = item.getValue();
                
                string p0 = item.getCloumnIndex().ToString();
                int idx = keys.IndexOf(p0);
                if (idx < 0)
                {
                    Console.Write(p0);
                    continue;
                }
                else if (itemValue == null)
                {
                    continue;
                }
                else if (item.getCloumnIndex() >= itemSizeDown)
                {
                    continue;
                }

                string[] varr = values[idx].ToString().Split(';');
                if (varr.Length < 3)
                {
                    Console.Write("格式不正確");
                    continue;
                }

                bool bia = surroundTypeA.IndexOf(varr[1]) < 0;
                bool bib = surroundTypeB.IndexOf(varr[1]) < 0;
                bool bic = surroundTypeC.IndexOf(varr[1]) < 0;
                bool bid = surroundTypeD.IndexOf(varr[1]) < 0;
                bool bie = surroundTypeE.IndexOf(varr[1]) < 0;
                bool bif = surroundTypeF.IndexOf(varr[1]) < 0;
                if (bia && bib && bic && bid && bie && bif)
                {
                    Console.Write("數據包不匹配");
                    continue;
                }

                bool ba = !bia && contenta.Length > 0 && itemValue.Equals(contenta);
                bool bb = !bib && contentb.Length > 0 && itemValue.Equals(contentb);
                bool bc = !bic && contentc.Length > 0 && itemValue.Equals(contentc);
                bool bd = !bid && contentd.Length > 0 && itemValue.Equals(contentd);
                bool be = !bie && contente.Length > 0 && itemValue.Equals(contente);
                bool bf = !bif && contentf.Length > 0 && itemValue.Equals(contentf);
                if (!ba && !bb && !bc && !bd && !be && !bf)
                {
                    continue;
                }

                int columnIndex = item.getCloumnIndex();
                if (dLinesCheck.Contains(columnIndex))
                {
                    continue;
                }
                dLinesCheck.Add(columnIndex);
            }
            dLinesCheck.Sort();
        }

        private void replaceContent(string path)
        {
            //生成新的一行数据追加到文件最后
            string[] keys;
            string[] values;

            string surrounfP = GlobalVariables.surrounPath + @"\" + path.Replace(GlobalVariables.firPath, "").Replace("x.txt", "").Replace(".txt", "") + ".ini";

            INIHelper.GetAllKeyValues("AAA", out keys, out values, surrounfP);
            string filePath = path.Replace("x.txt", "").Replace(".txt", "");

            string[] contents = new string[itemSize];
            int count = dLinesCheck.Count;
            for (int i = 0; i < count; i++)
            {
                int cIndex = (int)dLinesCheck[i];
                string tstr = "" + cIndex;
                string v = null;
                for (int j = 0; j < keys.Length; j++)
                {
                    string t = keys[j];
                    bool bl = t == tstr;
                    if (keys[j] == tstr)
                    {
                        v = values[j];
                    }
                }
                if (v == null)
                {
                    contents[cIndex] = "";
                }
                else
                {
                    string[] ar = v.Split(';');
                    if (ar.Length > 2 && ar[1] == "A")
                    {
                        contents[cIndex] = contenta;
                    }
                    else if (ar.Length > 2 && ar[1] == "B")
                    {
                        contents[cIndex] = contentb;
                    }
                    else if (ar.Length > 2 && ar[1] == "C")
                    {
                        contents[cIndex] = contentc;
                    }
                    else if (ar.Length > 2 && ar[1] == "D")
                    {
                        contents[cIndex] = contentd;
                    }
                    else if (ar.Length > 2 && ar[1] == "E")
                    {
                        contents[cIndex] = contente;
                    }
                    else if (ar.Length > 2 && ar[1] == "F")
                    {
                        contents[cIndex] = contentf;
                    }
                }
            }
            StringBuilder strBuilder = new StringBuilder();
            for (int j = 0; j < contents.Length; j++)
            {
                string con = contents[j];
                if (null == con)
                {
                    con = "";
                }
                strBuilder.Append(con + ",");
            }
            strBuilder.Remove(strBuilder.Length - 1, 1);
            string contentStr = strBuilder.ToString();

            RepContent rc = new RepContent();
            rc.path = path;
            rc.contentStr = contentStr;
            replaceContentList.Add(rc);
        }

        private void loadDataDown(string fileName)
        {
            itemSizeDown = 0;
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            while (!sr.EndOfStream)
            {
                string[] items = sr.ReadLine().Split(',');
                if (itemSizeDown == 0)
                {
                    itemSizeDown = items.Length;
                }
                break;
            }
            if (itemSizeDown == 0 )
            {
                itemSizeDown = itemSize;
            }
            sr.Close();
        }

        private void loadData(string fileName)
        {
            itemSize = 0;
            rowCount = 0;
            dLines.Clear();
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            while (!sr.EndOfStream)
            {
                string[] items = sr.ReadLine().Split(',');
                if (itemSize == 0)
                {
                    itemSize = items.Length;
                }
                for (int i = 0; i < items.Length; i++)
                {
                    if (items[i].Equals("-1"))
                    {
                        continue;
                    }
                    else if (items[i].Length <= 0)
                    {
                        continue;
                    }
                    dLine dline = new dLine();
                    dline.setValue(items[i].Equals("-1") ? "" : items[i]);
                    dline.setCloumnIndex(i);
                    dline.setRowIndex(rowCount);
                    dLines.Add(dline);
                }
                rowCount += 1;

            }
            sr.Close();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Replace_Load_1(object sender, EventArgs e)
        {

        }






    }
}
